package com.example.client.config;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

@Configuration
@Slf4j
public class WebSocketClientConfig {
    @Bean("pdool")
    public WebSocketClient pdoolWebSocketClient() {
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8090/websocket")) {
                //连接服务端时触发
                @Override
                public void onOpen(ServerHandshake handshakedata) {
//                    send("hello chongxin".getBytes());
                    log.info("websocket客户端和服务器连接成功");
                }

                //收到服务端消息时触发
                @Override
                public void onMessage(String message) {
                    log.info("websocket客户端收到消息={}", message);
                }

                //和服务端断开连接时触发
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    log.info("websocket客户端退出连接");
                }

                //连接异常时触发
                @Override
                public void onError(Exception ex) {
                    log.info("websocket客户端和服务器连接发生错误={}", ex.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
